package com.example.administrator.base.activity;

import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ListView;
import android.widget.SimpleAdapter;
import android.widget.Toast;

import com.example.administrator.base.baseActivity.BaseActivity;
import com.example.administrator.base.bean.ResentUserBean;
import com.example.administrator.base.R;
import com.example.administrator.base.util.GsonTools;
import com.example.administrator.base.util.SharedPreferencesUtils;
import com.lcodecore.tkrefreshlayout.RefreshListenerAdapter;
import com.lcodecore.tkrefreshlayout.TwinklingRefreshLayout;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import butterknife.ButterKnife;
import butterknife.InjectView;
import cn.pedant.SweetAlert.SweetAlertDialog;
import okhttp3.FormBody;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;

public class ResentUser extends BaseActivity {

    @InjectView(R.id.Toolbar)
    android.support.v7.widget.Toolbar Toolbar;
    @InjectView(R.id.list)
    ListView list;
    @InjectView(R.id.swip)
    TwinklingRefreshLayout swip;
    SimpleAdapter adapter;
    List<Map<String, Object>> datalist;
    String carnumber = "";
    Map<String, Object> map;
    SweetAlertDialog sweetAlertDialog;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_resent_user);
        ButterKnife.inject(this);
        sweetAlertDialog = new SweetAlertDialog(this, 5);
        sweetAlertDialog.setCanceledOnTouchOutside(false);
        sweetAlertDialog.setTitleText("加载中");
        datalist = new ArrayList<>();
        Toolbar.setTitle("赳猎人");
        Toolbar.setSubtitle("最近使用人");
        setSupportActionBar(Toolbar);
        Toolbar.setNavigationIcon(R.drawable.backbar);
        Toolbar.setNavigationOnClickListener(new android.view.View.OnClickListener() {
            @Override
            public void onClick(android.view.View v) {
                finish();
            }
        });
        Intent intent = getIntent();
        carnumber = intent.getStringExtra("car");
        adapter = new SimpleAdapter(this, datalist, R.layout.orderlistitem,
                new String[]{"name", "number", "img", "time"},
                new int[]{R.id.tv_pointName, R.id.tv_number, R.id.im_stage, R.id.tv_timex});
        list.setAdapter(adapter);
        list.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                String number = String.valueOf(datalist.get(position).get("number"));
                Intent intent = new Intent(Intent.ACTION_DIAL,Uri.parse("tel:"+number));
                intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                startActivity(intent);
            }
        });
        swip.setOnRefreshListener(new RefreshListenerAdapter() {
            @Override
            public void onRefresh(TwinklingRefreshLayout refreshLayout) {
                super.onRefresh(refreshLayout);
                datalist.clear();
                getResentUser(carnumber);
            }

            @Override
            public void onLoadMore(TwinklingRefreshLayout refreshLayout) {
                super.onLoadMore(refreshLayout);
                    swip.finishLoadmore();
            }
        });
        sweetAlertDialog.show();
        getResentUser(carnumber);
    }

    @Override
    protected void onResponseSuccess(Response response, String action) {

    }

    @Override
    protected void onResponseFailure(Throwable e, String action) {

    }

    /*获取最近使用人*/
    public void getResentUser(String  number) {
        final OkHttpClient client = new OkHttpClient();
        RequestBody formBody = new FormBody.Builder()
                .add("action", "GETTRANSRECORDINFO")
                .add("adminId", String.valueOf(SharedPreferencesUtils.getParam(ResentUser.this, "adminId", "")))
                .add("bicycleNo", number)
                .build();
        final Request request = new Request.Builder()
                .url("http://operate.99bicycle.com/OperateBicyclePro/operationperson?")
                .post(formBody)
                .build();
        new Thread(new Runnable() {
            @Override
            public void run() {
                Response response;
                try {
                    response = client.newCall(request).execute();
                    if (response.isSuccessful()) {
                        String string = response.body().string();
                        Log.i("2154541",string);
                        final ResentUserBean mse = GsonTools.changeGsonToBean(string, ResentUserBean.class);
                        if (mse != null) {
                            if (mse.getCode() == 1) {
                                int size = mse.getTransRecordInfo().size();
                                for (int i=0;i<size;i++){
                                    map = new HashMap<>();
                                    map.put("time", mse.getTransRecordInfo().get(i).getBorrowDateTime());
                                    map.put("name", mse.getTransRecordInfo().get(i).getRealName());
                                    map.put("number", mse.getTransRecordInfo().get(i).getPhone());
                                    map.put("img",R.drawable.calluser);
                                    datalist.add(map);
                                }
                                runOnUiThread(new Runnable() {
                                    @Override
                                    public void run() {
                                        Toast.makeText(ResentUser.this, "" + mse.getMessage(), Toast.LENGTH_LONG).show();
                                        adapter.notifyDataSetChanged();
                                        swip.finishRefreshing();
                                        swip.finishLoadmore();
                                        sweetAlertDialog.dismiss();
                                    }
                                });

                            } else {
                                runOnUiThread(new Runnable() {
                                    @Override
                                    public void run() {
                                        Toast.makeText(ResentUser.this, "" + mse.getMessage(), Toast.LENGTH_LONG).show();
                                        sweetAlertDialog.dismiss();
                                        swip.finishRefreshing();
                                        swip.finishLoadmore();
                                    }
                                });
                            }
                        }else {
                            runOnUiThread(new Runnable() {
                                @Override
                                public void run() {
                                    Toast.makeText(ResentUser.this, "数据异常请重试", Toast.LENGTH_LONG).show();
                                    sweetAlertDialog.dismiss();
                                }
                            });
                        }
                    } else {
                        throw new Exception("Unexpected code " + response);
                    }
                } catch (Exception e) {
                    runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            Toast.makeText(ResentUser.this, "数据异常请重试", Toast.LENGTH_LONG).show();
                            sweetAlertDialog.dismiss();
                        }
                    });
                    e.printStackTrace();
                }
            }
        }).start();


    }
}
